package com.lee.demo.html2pdf.controller;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.time.LocalDateTime;

/**
 * @author lyq
 * @time 2019/8/17 11:55
 */
@Controller
@Slf4j
public class HelloController {

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private ConverterProperties converterProperties;

    @RequestMapping("/hello")
    public String hello(ModelMap map) throws Exception {
        //1.填充模板
        WebContext context = new WebContext(request, response, request.getServletContext());
        map.put("name","lyq");
        LocalDateTime now = LocalDateTime.now();
        map.put("time", now);
        context.setVariables(map);
        String html = templateEngine.process("/index", context);
        log.info(html);
        //2.生成pdf
        OutputStream out = new FileOutputStream("d:/1.pdf");
        HtmlConverter.convertToPdf(html,out,converterProperties);

        return "/index";
    }
}
